package com.itheima.app.manager;

import cn.hutool.core.util.RandomUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.User;
import com.itheima.service.db.PhoneNumberService;
import com.itheima.service.db.UserService;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

import com.itheima.util.ConstantUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class PhoneNumberManager {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Reference
    private UserService userService;
    @Reference
    private PhoneNumberService phoneNumberService;

    public PhoneNumberManager() {
    }

    //修改手机号- 1 发送短信验证码
    public void sendVerificationCode() {

        //String code = RandomUtil.randomNumbers(6);/
        String code = "123456";//先写死数据
        System.out.println(code);
        //将验证码存入redis中
        stringRedisTemplate.opsForValue().set(ConstantUtil.SMS_CODE, code, Duration.ofMinutes(5));
    }

    //修改手机号 - 2 校验验证码
    public Map<String, Boolean> checkVerificationCode(String verificationCode) {
        String codeFromRedis = stringRedisTemplate.opsForValue().get(ConstantUtil.SMS_CODE);
        Boolean isPass;
        isPass= true;
        //进行比对
        if (!StringUtils.equals(codeFromRedis, verificationCode)) {
            isPass = false;
            throw new RuntimeException("验证码错误");
        }
            HashMap<String, Boolean> map = new HashMap();
            map.put("verification", isPass);
            return map;

    }

    //修改手机号 - 3 保存
    public void saveNewPhoneNumber(String phone) {
        Long userId = UserHolder.get().getId();
        //查询用户信息
        User user = userService.findByUserId(userId);
        //用手机号查询用户信息能否查询到
        if (userService.findByPhone(phone) != null) {
            //用户数据不为空  查得到 手机号已经存在不能改
            throw new RuntimeException("手机号已经存在");
        } else {
            //查不到 手机号不存在 可以修改
            user.setPhone(phone);
            phoneNumberService.saveNewPhoneNumber(user);
        }
    }
}
